<template>
  <div class="about">
    <h1>{{ id ? "编辑" : "新建" }}文章</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select
          v-model="model.categories"
          placeholder="请选择"
          class="m-2"
          size="large"
          multiple
        >
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>

      <el-form-item label="详情">
        <VueEditor
          useCustomImageHandler
          @image-added="handleImageAdded"
          v-model="model.body"
        ></VueEditor>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { postNewCategory, getDetail, putDetail, getList } from "@/api";
import { ElMessage } from "element-plus";
import { VueEditor } from "vue3-editor";
export default {
  props: {
    id: {},
  },
  components: {
    VueEditor,
  },
  setup(props) {
    var model = ref({});
    const router = useRouter();
    const categories = ref({});
    async function save() {
      let res = props.id
        ? await putDetail("articles", props.id, model)
        : await postNewCategory("articles", model);
      console.log(res);
      router.push("/articles/list");
      ElMessage({
        message: "保存成功",
        type: "success",
      });
    }
    async function fetch() {
      const res = await getDetail("articles", props.id);
      model.value = res.data;
    }
    async function fetchParens() {
      const res = await getList("categories");
      categories.value = res.data;
    }
    onBeforeMount(() => {
      // 组件初次在页面渲染之前（创建阶段）唯一一次
      props.id && fetch();
      fetchParens();
    });

    async function handleImageAdded(
      file,
      Editor,
      cursorLocation,
      resetUploader
    ) {
      const formData = new FormData();
      formData.append("file", file);

      const res = await axios({
        url: "http://localhost:3000/admin/api/upload",
        method: "POST",
        data: formData,
      });
      Editor.insertEmbed(cursorLocation, "image", res.data.url);
      resetUploader();
    }
    return { model, save, categories, handleImageAdded };
  },
};
</script>

<style></style>
